import QQMapWX from '../../yali-sdk/lib/qqmap-wx-jssdk.min.js';
import { addNotifier, removeNotifier, notify } from '../../yali-sdk/utils/NotifyRegistryCenter';
function fomatFloat(src) {
  return Math.floor(src * 100) / 100;
} 

export default function getLocation(callback) {
  // 获取当前位置
  const qqmapsdk = new QQMapWX({
    key: 'PMFBZ-RANLG-C4OQT-IKVXS-PO3FQ-D5FEO' // 必填
  });
  wx.getLocation({
    type: 'wgs84',
    success: (res) => {
      const location = wx.getStorageSync('location'); 
      // 如果缓存
      if (fomatFloat(location.latitude) != fomatFloat(res.latitude) || fomatFloat(location.longitude) != fomatFloat(res.longitude)) {
        //2、根据坐标获取当前位置名称，显示在顶部:腾讯地图逆地址解析
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude,
          },
          coord_type: 1,
          get_poi:1,
          success: (addressRes) => {
            const result = addressRes.result;
            const newLocation = {
              latitude: res.latitude,
              longitude: res.longitude,
              address: result.formatted_addresses.recommend,
              ad_info: {
                province: result.ad_info.province,
                city: result.ad_info.city,
                zone: result.ad_info.district
              },
              pois: result.pois
            };
            wx.setStorageSync('location', newLocation);
            getApp().globalData.latitude = res.latitude;
            getApp().globalData.longitude = res.longitude;
            getApp().globalData.address = result.formatted_addresses.recommend;
            callback && typeof callback == 'function' && callback(newLocation)
            notify && notify('updateLocation', newLocation.address)
          }
        });
      } else {
        getApp().globalData.latitude = location.latitude;
        getApp().globalData.longitude = location.longitude;
        getApp().globalData.address = location.address;
        callback && typeof callback == 'function' && callback(location)
      }
    }
  });
}